package com.example.demo;
import com.example.demo.Controller.FunctionMapImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.interceptor.SQLInterceptor;
import org.ssssssss.magicapi.model.FunctionInfo;
import org.ssssssss.magicapi.model.RequestEntity;
import org.ssssssss.magicapi.modules.BoundSql;
import org.ssssssss.magicapi.provider.MagicAPIService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 拦截SQL请求
 */
@Component
public class MysqlExInterceptor implements SQLInterceptor {

    /**
     * 1.1.1 新增
     *
     * @since 1.1.1
     * @param boundSql      SQL信息
     * @param requestEntity 请求信息
     */
    @Autowired
    MagicAPIService magicAPIService;
    @Autowired
    FunctionMapImpl functionMap;
    @Override
    public void preHandle(BoundSql boundSql, RequestEntity requestEntity) {
        // 打印log
        Logger logger = LoggerFactory.getLogger(requestEntity == null ? "Unknown" : requestEntity.getMagicScriptContext().getScriptName());
        logger.info("MysqlExInterceptor preHandle");
        magicAPIService.functionList().forEach(functionInfo -> {
            logger.info(functionInfo.getId());
        });
        HashMap<String, String> preMap = functionMap.getPreMap();
        preMap.forEach((key,value)->{
            logger.info(key+":"+value);
            logger.info(requestEntity.getApiInfo().getId());

            if (key.equals(requestEntity.getApiInfo().getId())){
                FunctionInfo functionInfo = magicAPIService.getFunctionInfo(value);
//                logger.info("magicAPIService.getFunctionInfo(value):"+functionInfo.getName());
//                requestEntity.getParameters().forEach((key1,value1) ->{
//                    logger.info(key1+":"+value1);
//                });
                String fullPath = "/"+ magicAPIService.getGroup(functionInfo.getGroupId()).getPath() + "/"+ functionInfo.getPath();
//                logger.info("fullPath:"+fullPath);
                logger.info(requestEntity.getParameters().toString());
                Object invoke = magicAPIService.invoke(fullPath, requestEntity.getParameters());
                logger.info("invoke"+invoke.toString());
                if (invoke != null){
                    List<Object> parameters = new ArrayList<>();
                    Map<Object,Object> magicFunctionReturnMap = (Map<Object, Object>) invoke;
                    logger.info("magicFunctionReturnMap"+magicFunctionReturnMap.isEmpty());
                    // 按requestEntity内的参数顺序依次填入到boundSQL内
                    requestEntity.getParameters().forEach((paramKey,paramValue)->{
                        if (magicFunctionReturnMap.get(paramKey) != null){
                            paramValue = magicFunctionReturnMap.get(paramKey);
                            parameters.add(paramValue);
                        }
                    });
                    boundSql.setParameters(parameters);
                    logger.info("boundSql"+Arrays.toString(boundSql.getParameters()));
                }

            }
        });

    }

    /**
     * @since 1.7.2
     * @param boundSql	SQL信息
     * @param result	执行结果
     * @param requestEntity	请求信息
     */
    @Override
    public Object postHandle(BoundSql boundSql, Object result, RequestEntity requestEntity){
        Logger logger = LoggerFactory.getLogger(requestEntity == null ? "Unknown" : requestEntity.getMagicScriptContext().getScriptName());
        logger.info("MysqlExInterceptor postHandle");
//        HashMap<String, String> postMap = functionMap.getPostMap();
//        postMap.forEach((key,value)->{
//            if (key.equals(requestEntity.getApiInfo().getId())){
//                FunctionInfo functionInfo = magicAPIService.getFunctionInfo(value);
//                magicAPIService.invoke(functionInfo.getPath(),requestEntity.getParameters());
//            }
//        });
        return result;
    }


}
